import os

from django.conf import settings
from datetime import date
from django import forms
from django.shortcuts import render_to_response
from django.http import HttpResponse

from Projekt.UnitTestSystem.SingleTester import SingleTester


def index(request):
    return render_to_response('index.html')
    

def handle_uploads(request, keys, additional_directory = ''):
    saved = []
    
    upload_dir = date.today().strftime(settings.UPLOAD_PATH)
    upload_full_path = os.path.join(settings.MEDIA_ROOT, upload_dir)
    
    if additional_directory != '':
        upload_full_path += '/' + additional_directory
    
    if not os.path.exists(upload_full_path):
        os.makedirs(upload_full_path)

    for key in keys:
        if key in request.FILES:
            upload = request.FILES[key]
            while os.path.exists(os.path.join(upload_full_path, upload.name)):
                upload.name = '_' + upload.name
                
            dest = open(os.path.join(upload_full_path, upload.name), 'wb')
            for chunk in upload.chunks():
                dest.write(chunk)
            dest.close()
            saved.append((key, os.path.join(upload_dir, upload.name)))
    # returns [(key1, path1), (key2, path2), ...]
    return saved

class UploadFileForm(forms.Form):
    file  = forms.FileField()
    
def userFileUpload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            saved = handle_uploads(request, ['file'], 'user')
            return render_to_response('main.html')
    
    else:
            form = UploadFileForm()
            return render_to_response('fileUpload.html', {'form': form})
        
def testerFileUpload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            saved = handle_uploads(request, ['file'], 'tester')
            return render_to_response('main.html')
    else:
            form = UploadFileForm()
            return render_to_response('testerUpload.html', {'form': form})
        
def testExecuter(request):
    userTestPath = os.path.join(settings.UPLOAD_PATH, 'user/') + 'SimpleUserCode'
    #testTestPath = os.path.join(settings.UPLOAD_PATH, 'tester/') + 'SimpleTest'
    test = SingleTester(userTestPath, 'Testeric')
    testOut = test.executeTest()
    return render_to_response('results.html', {'testOut' : testOut})
    